package com.huixin.powermonitor.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import com.huixin.powermonitor.common.GetPath;
import com.huixin.powermonitor.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传下载接口")
public class UploadController {
    @Resource
    private GetPath getPath;

    //获取文件扩展名
    private String getFileExtension(String fileName) {
        int i = fileName.lastIndexOf(".");
        if (i > 0 && i < fileName.length() - 1) {
            return fileName.substring(i + 1);
        }
        return "";
    }

    //获取文件名
    private String getFileName(String fileName) {
        int i = fileName.lastIndexOf(".");
        if (i > 0 && i < fileName.length() - 1) {
            return fileName.substring(0, i);
        }
        return fileName;
    }

    // 上传接口
    @PostMapping("/avatar")
    @ApiOperation("上传头像文件")
    public Result uploadAvatar(String fileName, @RequestParam("file") MultipartFile file) {
        String flag = getFileName(fileName);
        String ext = getFileExtension(fileName);
        try {
            if (!FileUtil.isDirectory(getPath.getProjectPath() + "/avatar/")) {
                FileUtil.mkdir(getPath.getProjectPath() + "/avatar/");
            }
            FileUtil.writeBytes(file.getBytes(), getPath.getProjectPath() + "/avatar/" + flag + "." + ext);
            return Result.suc(flag);
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/avatar/{flag}")
    @ApiOperation("获取头像文件")
    public void getAvatar(@PathVariable("flag") String flag, HttpServletResponse response) throws IOException {
        String filePath = getPath.getProjectPath() + "/avatar/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String targetFileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        System.out.println(targetFileName);
        try {
            if (StrUtil.isNotEmpty(targetFileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + targetFileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                System.out.println("文件下载成功");
            }
        } catch (IORuntimeException e) {
            System.out.println(e.getMessage());
        }
    }

    @PostMapping("/image")
    @ApiOperation("上传图片文件")
    public Result uploadImage(String fileName, @RequestParam("file") MultipartFile file) {
        String flag = getFileName(fileName);
        String ext = getFileExtension(fileName);
        try {
            if (!FileUtil.isDirectory(getPath.getProjectPath() + "/image/")) {
                FileUtil.mkdir(getPath.getProjectPath() + "/image/");
            }
            FileUtil.writeBytes(file.getBytes(), getPath.getProjectPath() + "/image/" + flag + "." + ext);
            return Result.suc(flag);
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/image/{flag}")
    @ApiOperation("获取图片文件")
    public void getImage(@PathVariable("flag") String flag, HttpServletResponse response) throws IOException {
        String filePath = getPath.getProjectPath() + "/image/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String targetFileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        System.out.println(targetFileName);
        try {
            if (StrUtil.isNotEmpty(targetFileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + targetFileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                System.out.println("文件下载成功");
            }
        } catch (IORuntimeException e) {
            System.out.println(e.getMessage());
        }
    }

    @GetMapping("/file/{flag}")
    @ApiOperation("获取普通文件")
    public void getFile(@PathVariable("flag") String flag, HttpServletResponse response) throws IOException {
        String filePath = getPath.getProjectPath() + "/file/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String targetFileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        System.out.println(targetFileName);
        try {
            if (StrUtil.isNotEmpty(targetFileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + targetFileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                System.out.println("文件下载成功");
            }
        } catch (IORuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}